package com.leo.javase.thread;

/**
 * 利用两个线程，对一个整形成员变量进行变化，一个对其增加，一个对其减少，
 * 利用线程间的通信，实现该整形变量0101这样交替的变更
 * 
 * @author Administrator
 */
public class NumberCommunicate {

	public static void main(String[] args) {
		final Data data = new Data();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					data.incr();
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					data.decr();
				}
			}
		}).start();
	}
	
}
class Data{
	private int count = 0;
	
	private boolean flag = true;
	
	public synchronized void incr(){
		if(!flag){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(++count);
		flag = false;
		notify();
	}
	
	public synchronized void decr(){
		if(flag){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(--count);
		flag = true;
		notify();
	}
	
}
